package com.lin.manager.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lin.manager.system.dao.SysUserRoleDao;
import com.lin.manager.system.entity.SysUserRoleEntity;
import com.lin.manager.login.model.vo.LoginUserVo;
import com.lin.manager.system.service.SysRoleService;
import com.lin.manager.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者: 林江
 * @创建时间: 2024/3/12
 * @功能:
 */
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {
    @Autowired
    SysUserRoleDao sysUserRoleDao;
    @Autowired
    SysRoleService sysRoleService;

    @Override
    public List<SysUserRoleEntity> findByRoleId(Integer roleId) {
        LambdaQueryWrapper<SysUserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRoleEntity::getRoleId, roleId);
        return sysUserRoleDao.selectList(wrapper);
    }

    @Override
    public List<SysUserRoleEntity> findByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRoleEntity::getUserId, userId);
        return sysUserRoleDao.selectList(wrapper);
    }

    @Override
    public void binding(List<SysUserRoleEntity> roleMenus) {
        for (SysUserRoleEntity roleMenu : roleMenus) {
            sysUserRoleDao.insert(roleMenu);
        }
    }

    @Override
    public void deleteByRoleId(Integer roleId) {
        sysUserRoleDao.delete(new LambdaQueryWrapper<SysUserRoleEntity>().eq(SysUserRoleEntity::getRoleId, roleId));
    }

    @Override
    public void deleteByUserId(Long userId) {
        sysUserRoleDao.delete(new LambdaQueryWrapper<SysUserRoleEntity>().eq(SysUserRoleEntity::getUserId, userId));
    }

    @Override
    public LoginUserVo findLoginRoleByUserId(Long userId) {
        List<SysUserRoleEntity> userRoles = this.findByUserId(userId);
        List<Integer> roleIds = userRoles.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
        return sysRoleService.findLoginRoleByRoleIds(roleIds);
    }

}
